// JavaScript Document
$(document).ready(function() {
	//var module_alert = $("#module").val(); //name of the module/functionality to display in alert box
	var module_alert = "newsletter to publish" 			   
	//Function to publish newsletters
	$("#edit-publish").click(function() {
		if (checkbox_values = getSelectedCheckBoxes(module_alert)) {
			var n =0;
			for(i=0;i<checkbox_values.length;i++){
			     strnewsletter = $('#newsletterStatus'+checkbox_values[i]).html();
				 n = strnewsletter.search('Published');
				 if(n >= 0 ){
					 openAlertDialog(400, 125, 'Information', 'Please select the newsletter which is in draft status');
					 return false;
				 }

			}
            

			//open the confirm dialog before deactivate
			openConfirmDialog("publish", checkbox_values, 400, 125, 'Are you Sure?', 'Do you want to publish the selected newsletters?', "bulk");			
		}
		//return without submitting the page
        return false;
	});
	
	//Function to call filter functionalities through AJAX
    $("#edit-apply").click(function () {
       	applyNewsletterFilterAction(1);
        return false;
    });
	
	//Date picker for date search in message listing pages
    $('#edit-news-search-date').datepicker({dateFormat:'yy-mm-dd'});
	
	$("#CreateNewsletter").click(function() {
		//addEditNewsletterDialog('new', 750, 450, 'Create Newsletter');
    openDialog('createnewsletter', 'new', 750, 450, 'Create Newsletter');
	});
});

//Function to ignore the selected messages
function publishNewsletters (ok, fn, id, mode) {
	if (ok) {
		$(".ui-dialog-buttonpane").remove();
		$('#dialog').html('<div style="padding-top: 10px; padding-left: 150px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
	}
	//AJAX call to update the status of the messages
	$.ajax({
		type : "POST",
		url : baseurl+"newsletter/actions/"+fn,
		data : "checkbox_values="+id,
		async : true,
		cache : false,
		success : function (msg) {
			if (msg == "success") {
				//close the popup window
				$("#dialog").dialog("destroy");
				
				//unselect the checkboxes
				if (mode == "bulk") {
					$('input[@name=checkBoxList]:checked').each(function(){
						$("#newsletterStatus"+($(this).val())).html("<p>Published</p>");
						this.checked = false;
					});
					if ($("#checkAll")) {
						$("#checkAll").attr('checked', false);
					}			
				}
			}
		},
    error : function (res) {
      handleRequestError(res);
    }
	});	
}

//Function to list the newsletter subscription information
function newsletterSubscriptionInfo (newsletter_id) {
	//AJAX call to load the subscription information based on the newsletter id
	$.ajax({
		type : "POST",
		url : baseurl+"newsletter/subscription.info/"+newsletter_id,
		async : true,
		cache : false,
		success : function (msg) {
			$('#dialog').html(msg);
			
			//Function to check all checkboxes
			$("#checkAll_Popup").click(function()	{
					var checked_status = this.checked;
					//get the list of checkbox and change the status to checked
					$("input[@name=checkBoxList_Popup]").each(function() {
							this.checked = checked_status;
					});
			});				
			
			$("#ExportSelected").click(function() {
				var checkbox_values = getSelectedValues_Popup();
				$("#Subscriptionlist_Export").val(checkbox_values);
				$("#selectedExportException").val(getAllValues_Popup());
				$("#selectedExport").val("ExportSelected");				
				$("#SubscriberslistFrm").submit();
			});
			$("#ExportAll").click(function() {
				$("#selectedExport").val("ExportAll");
				$("#SubscriberslistFrm").submit();
			});
		},
    error : function (res) {
      handleRequestError(res);
    }
	});	
}

//Function to list the newsletter subscription information
function newsletterSubscriptionView (newsletter_id) {
	$.ajax({
		type : "POST",
		url : baseurl+"newsletter/actions/view/"+newsletter_id,
		async : true,
		cache : false,
		success : function (msg) {
			//Display the returned HTML content
			$('#dialog').html(msg);
			//enable the button while loading the content
			$(".ui-dialog-buttonpane").show();
		},
		error : function (res) {
			handleRequestError(res);
		}
	});
}

//Function to implement the filter action for messages
function applyNewsletterFilterAction (pageno) {
	//prepare the field values for filtering
	var search_newsletter = $.trim($("#edit-news-search-newsletter").val());
	var search_status = $("#edit-news-search-status").val();
	var search_date = $.trim($("#edit-news-search-date").val());
	var sort = $('#hid_sort').val();
	$('#hid_pageno').val(pageno);

	//page loading animation
	pagination_loading("page");		

	$.ajax({
		type : "POST",
		url : baseurl+"newsletter/actions/filter",
		data : "search_newsletter="+encodeURIComponent(search_newsletter)+"&search_status="+search_status+"&search_date="+search_date+(pageno>1?'&page_no='+pageno:'')+(sort!=""?'&sorting='+sort:''),
		async : true,
		cache : false,
		success : function (msg) {
			$("#listingResultset").html(msg);
			var limit = $('#hid_limit').val();
			var page = pageno;
			var counter = $('#hid_totalRec').val();
			//create pagination links through AJAX
			create_pagination_links(counter, page, limit);
		},
		error : function (res) {
			handleRequestError(res);
		}
	});
}

//Function to create pagination links while filtering
function create_pagination_links (counter, page, limit) {
	var str = "";
    var to = page*limit;
	
	str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
	if (page > 1) {
		str += '<a href="javascript:void(0)" onclick = "applyNewsletterFilterAction('+(page-1)+')" class="red"><< Previous</a>';
	}
	if (to < counter) {
		str += '<span class="red"> |</span><a href="javascript:void(0)" onclick = "applyNewsletterFilterAction('+(page+1)+')" class="red">Next >></a>';
	}
	
	//No records found when no result
	if (counter <= 0) {
		str = '';
	}

	$("#pagingdivtop").html(str);
	$("#pagingdivbottom").html(str);	
}

//Function to get the individual testimonial to display in detail page
function addEditNewsletter (id) {
	$.ajax({
		type : "POST",
		url : baseurl+'newsletter/actions/'+id,
		async : true,
		cache : false,
		success : function (msg) {
			//Display the returned content in dialog window
			$('#dialog').html(msg);
			
			$("#edit-newsletter-desc").css("width", "712px");
			$("#edit-newsletter-desc").css("height", "175px");
			//Date picker for date search in message listing pages
			createDatePicker('edit-newsletter-actdate',0);
			createDatePicker('edit-newsletter-expdate',0);
			if(!editor){
					editor = CKEDITOR.replace( 'edit-newsletter-desc',{
							skin : 'v2',
							resize_enabled:false,
							enterMode: Number(2),
							removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
					});
			}else{
					if (CKEDITOR.instances['edit-newsletter-desc']) {
							CKEDITOR.remove(CKEDITOR.instances['edit-newsletter-desc']);
					}
					editor = CKEDITOR.replace( 'edit-newsletter-desc',{
							skin : 'v2',
							resize_enabled:false,
							enterMode: Number(2),
							removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
					});
			}
      $('.ui-dialog').css("filter","");
		},
		error : function (res) {
			handleRequestError(res);
		}
	});	
}


//Function to convert to date string format
function convertDateString (date) {
	var split_date = date.split("-");
	var date_string = split_date[2] +"/"+ split_date[0] +"/"+ split_date[1];
	return date_string;
}

//Function to save subjects
function saveNewsletter (id) {
	var newsletter_title = $.trim($("#edit-newsletter-title").val());
	var newsletter_desc = editor.getData();
	//var newsletter_desc = $("#edit-newsletter-desc").val();
	var newsletter_actdate = $.trim($("#edit-newsletter-actdate").val());
	var newsletter_expdate = $.trim($("#edit-newsletter-expdate").val());
	var newsletter_status = $("#edit-newsletter-status").val();
	
	var validformat=/^\d{4}\/\d{2}\/\d{2}$/ //Basic check for format validity
		
	//code to validate the fields
	var lines = 10;
	var str = "";
	if(newsletter_title == ""){
		str += "Please enter the Newsletter title";
		lines+=18;
	}
	if (newsletter_title != "") {
		if(newsletter_title.length > 50) {
			if(str!="")
					str+= "<br/>";
			str += "Title should not be more than 50 characters";
			lines+=18;
		}
	}
	var stripped_desc = stripHTML(newsletter_desc);
	if ($.trim(stripped_desc) != "") {
		if(stripped_desc.length > 1000) {
			if(str!="")
					str+= "<br/>";
			str += "Description should not be more than 1000 characters";
			lines+=18;
		}
	}
	if(newsletter_actdate==""){
		if(str!="")
				str+= "<br/>";
		str += "Please enter(or)select Activation date from the calender";
		lines+=18;
	}
	
	var actdate_str = convertDateString(newsletter_actdate);
	var expdate_str = convertDateString(newsletter_expdate);
	
	var datetestflag = 0;
	if (newsletter_actdate != "") {
		if(!validformat.test(actdate_str)) {
			if(str!="")
					str+= "<br/>";
			str += "Please enter valid date in Activation date field";
			lines+=18;
			datetestflag = 1;
		}
	}
	else{
		datetestflag = 1
	}

	if (newsletter_expdate != "") {	
		if(!validformat.test(expdate_str)) {
			if(str!="")
					str+= "<br/>";
			str += "Please enter valid date in Expiration date field";
			lines+=18;
			datetestflag = 1;
		}
	}
	
	if(datetestflag == 0){
		if (newsletter_expdate != "") {
			if (!fromGreaterThanTo(actdate_str, expdate_str)) {
				if(str!="")
						str+= "<br/>";
				str += "Expiration date should be greater than the Activation date";
				lines+=18;
			}		
		}
	}


	if(newsletter_status == -1){
		if(str!="")
				str+= "<br/>";
		str += "Please select the status from dropdown";
		lines+=18;
	}

	if (str != "") {
		resize_dialog(750, 450+lines);
		styleStatusMessages(str, "statusMessage", "failure");
		$('#dialog').scrollTop(0);
		return;
	}

	//page loading animation
	$(".ui-dialog-buttonpane").remove();
	var content = $('#dialog').html();
  $('#dialog').html('<div style="padding-top:130px; padding-left:320px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');	
	
	$.ajax({
		type : "POST",
		url : baseurl+"newsletter/actions/save",
		data : "newsletter_id="+id+"&newsletter_title="+ encodeURIComponent(newsletter_title) +"&newsletter_desc="+encodeURIComponent(newsletter_desc)+"&newsletter_actdate="+newsletter_actdate+"&newsletter_expdate="+newsletter_expdate+"&newsletter_status="+newsletter_status,
		async : true,
		cache : false,
		success : function (msg) {
			if (msg == "success") {
				$("#dialog").dialog("destroy");

				if (id == "new") {
					var totalrec = parseInt($("#hid_totalRec").val()) + 1;
					//reload the subject listing
					reloadListingData($("#hid_limit").val(), 1, "", totalrec, baseurl+"newsletter", "page");
				}
				else {
					$("#newsletterDetails"+id).html('<p>'+newsletter_title+'</p>');
					$("#newsletterStatus"+id).html('<p>'+newsletter_status+'</p>');
				}
			}
			else if (msg == "not_unique") {
				$.get(baseurl+'newsletter/actions/'+id, function callback(res){
					//reload the newsletter content																												
        	$('#dialog').html(res);
					
					//modifiy the description field and add editor
					$("#edit-newsletter-desc").css("width", "712px");
					$("#edit-newsletter-desc").css("height", "175px");
					//Date picker for date search in message listing pages
					createDatePicker('edit-newsletter-actdate',0);
					createDatePicker('edit-newsletter-expdate',0);
					if(!editor){
							editor = CKEDITOR.replace( 'edit-newsletter-desc',{
									skin : 'v2',
									resize_enabled:false,
									enterMode: Number(2),
									removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
							});
					}else{
							if (CKEDITOR.instances['edit-newsletter-desc']) {
									CKEDITOR.remove(CKEDITOR.instances['edit-newsletter-desc']);
							}
							editor = CKEDITOR.replace( 'edit-newsletter-desc',{
									skin : 'v2',
									resize_enabled:false,
									enterMode: Number(2),
									removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
							});
					}
					$('.ui-dialog').css("filter","");
					
					//reload the new title and display the error message
					$("#edit-newsletter-title").val(newsletter_title);
					editor.setData(newsletter_desc);
					$("#edit-newsletter-actdate").val(newsletter_actdate);
					$("#edit-newsletter-expdate").val(newsletter_expdate);
					$("#edit-newsletter-status").val(newsletter_status);
					styleStatusMessages("Newsletter title already exists.", "statusMessage", "failure");
					$('#dialog').scrollTop(0);
				});
			}
		},
		error : function (res) {
			handleRequestError(res);
		}
	});
}

//Function to open view detail dialog box
function openViewDetailDialog(id, width, height, title){
	$("#NewsletterTitle").val(title);
	var wid = width;
	var heit = height;
	var buttons = false;
	$('#dialog').dialog({
		autoOpen: false,
		width: wid,
		height: heit,
		bgiframe: true,
		resizable: false,
		title:title,
		modal: true,
		show: 'puff',
		close: function () {
			$(this).dialog('destroy');
		}
	});
	$('#dialog').dialog('open');
	var h = heit;
	if(buttons){
			h = heit-95;
	}else{
			h = heit-40;
	}
	$('#dialog').css({
		'overflow-y':'auto',
		'width': (wid-16)+'px',
		'height':h+'px'
	}).show();

	//hide the button while loading the content
	$(".ui-dialog-buttonpane").hide();
	$('#dialog').html('<div style="padding-top:55px; padding-left:200px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');		
	newsletterSubscriptionView(id);
}

//Function to get the filter field data for newsletter
function filterdata_newsletter(){
	//prepare the field values for filtering	
	var search_newsletter = $.trim($("#edit-news-search-newsletter").val());
	var search_status = $("#edit-news-search-status").val();
	var search_date = $.trim($("#edit-news-search-date").val());
	var data = "&search_newsletter="+encodeURIComponent(search_newsletter)+"&search_status="+search_status+"&search_date="+search_date;
	return data;
}

//function to close the dialog window
function closeDialog () {
	$("#dialog").dialog("destroy");
}

//function to open edit newsletter dialog
function editNewsletter (id) {
	reopen_dialog(750, 450, $("#NewsletterTitle").val());
	addEditNewsletter(id);	
}

//function to view subscribers
function viewSubscribers (id) {
	reopen_dialog(630, 535, $("#NewsletterTitle").val());
	newsletterSubscriptionInfo(id);	
}

//function to export subscribers
function exportSubscribers () {
	$("#selectedExport").val("ExportAll");
	$("#SubscriberslistFrm").submit();	
}